package csu.web.mypetstore.persistence.impl;

import csu.web.mypetstore.persistence.CartDao;
import csu.web.mypetstore.persistence.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class CartDaoImpl implements CartDao {
    private static String getItem = "SELECT ITEM FROM CART WHERE USERNAME = ?";
    private static String insertItem = "INSERT INTO CART (USERNAME, ITEM) VALUES (?, ?)";
    private static String removeItem = "DELETE FROM CART WHERE USERNAME = ? AND ITEM = ?";

    private static String getCartByUsername="SELECT * FROM CART WHERE USERNAME = ?";
    @Override
    public List<String> getItemByUsername(String username) {
        List<String> items = new ArrayList<>();
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(getItem);
            preparedStatement.setString(1,username);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String item = resultSet.getString(1);
                items.add(item);
            }
            //关闭资源
            DBUtil.closeResultSet(resultSet);
            DBUtil.closePreparedStatement(preparedStatement);
            DBUtil.closeConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();    //打印异常堆栈信息
        }
        return items;
    }

    @Override
    public void insertItem(String username, String item) {
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(insertItem);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,item);
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void removeItem(String username, String item) {
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(removeItem);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,item);
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
